package com.lzy.cloud.permission.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzy.cloud.permission.dtos.PermissionDto;
import com.lzy.cloud.permission.entity.Permission;
import com.lzy.cloud.permission.mapper.PermissionMapperExt;
import com.lzy.cloud.permission.service.PermissionService;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.utils.DozerUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by WIN7 on 2018/5/16.
 */
@Service
public class PermissionServiceImpl implements PermissionService{

    @Autowired
    PermissionMapperExt permissionMapperExt;

    @Override
    public Boolean insert(PermissionDto permissionDto) {
        if(permissionDto != null){
            if(permissionDto.getCode() != null){
                PermissionDto dto = checkCode(permissionDto.getCode());
                Ensure.that(dto).isNull("00040005");
            }
        }
        return permissionMapperExt.insertSelective(DozerUtils.map(permissionDto, Permission.class))>0;
    }

    @Override
    public Boolean delete(Long id) {
        return permissionMapperExt.deleteByPrimaryKey(id)>0;
    }

    @Override
    public Boolean update(PermissionDto permissionDto) {
        if(permissionDto != null){
            if(permissionDto.getCode() != null){
                PermissionDto dto = checkCode(permissionDto.getCode());
                Ensure.that(dto).isNull("00040005");
            }
        }
        return permissionMapperExt.updateByPrimaryKeySelective(DozerUtils.map(permissionDto,Permission.class))>0;
    }

    @Override
    public List<PermissionDto> selectAllPermission(PermissionDto permissionDto) {
        return permissionMapperExt.selectList(permissionDto);
    }

    @Override
    public PageInfo selectList(Pager pager, PermissionDto permissionDto) {
        if (pager != null)
            PageHelper.startPage(pager.getPageNum(), pager.getPageSize());
        List<PermissionDto> permissionDtoList = permissionMapperExt.selectList(permissionDto);
        return new PageInfo(permissionDtoList);
    }

    @Override
    public PermissionDto selectById(Long id) {
        return DozerUtils.map(permissionMapperExt.selectByPrimaryKey(id),PermissionDto.class);
    }

    @Override
    public PermissionDto selectPermission(PermissionDto permissionDto) {
        return permissionMapperExt.selectPermission(permissionDto);
    }

    /**
     * 权限编码判重
     * @param code
     * @return
     */
    public PermissionDto checkCode(String code){
        PermissionDto permission = new PermissionDto();
        permission.setCode(code);
        return permissionMapperExt.selectPermission(permission);
    }
}
